package com.zsoft.index;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class IndexSearch {

	public static void main(String[] args) throws IOException, ParseException {
		search("java");

	}

	public static String search(String key) throws IOException, CorruptIndexException, ParseException {
		String indexDir = "H:\\lucene_index\\";
		Directory dir = FSDirectory.open(new File(indexDir));
		IndexSearcher search = new IndexSearcher(IndexReader.open(dir));

		// QueryParser par = new MultiFieldQueryParser(Version.LUCENE_36, new
		// String[] { "name" }, new StandardAnalyzer(
		// Version.LUCENE_36));
		// Query query = par.parse("java");

		// Term t = new Term("name", "mongo*");
		// Query query = new TermQuery(t);
		Query query1 = new WildcardQuery(new Term("name", "*"+key+"*"));// 通配符搜索
		Query query2 = new TermQuery(new Term("type", "d"));// 关键字全文匹配
		// Query query=new FuzzyQuery(new Term("name", "java*,mongo*"));//模糊搜索

		// query=new WildcardQuery(new Term("*java*"));

		BooleanQuery boolean_query = new BooleanQuery();
		// boolean_query.add(query1, BooleanClause.Occur.MUST);
		// boolean_query.add(query2, BooleanClause.Occur.MUST);
		boolean_query.add(query1, BooleanClause.Occur.MUST);
		boolean_query.add(query2, BooleanClause.Occur.MUST);
		TopDocs hits = search.search(boolean_query, 1000);
		System.out.println("----找到了数据-" + hits.totalHits + "--条");
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < hits.scoreDocs.length; i++) {
			ScoreDoc doc = hits.scoreDocs[i];
			Document docx = search.doc(doc.doc);
			sb.append(docx.get("name") + "<br/><span>&nbsp;&nbsp;&nbsp;<a href='" + docx.get("path") + "'>"
					+ docx.get("type") + "</a><br/>");
		}

		return sb.toString();
	}
}
